package com.ssyc.common.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ssyc.common.R;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.view.statelayoutlib.StateLayoutManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by lenovo on 2016/9/7.
 */
public abstract class CommonFragment extends Fragment {


    //状态控制视图
    protected StateLayoutManager statusLayoutManager;


    //跟布局
    protected View rootView;


    //通用头布局
    protected LinearLayout llHead;
    protected RelativeLayout rlBack;
    protected TextView tvTitle;

    //状态栏
//    private StatusBarView statusBarView;


    //基类宿主Acitvity
    protected Activity activity;

    private static final String STATE_SAVE_IS_HIDDEN = "STATE_SAVE_IS_HIDDEN";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        rootView = View.inflate(getContext(), R.layout.fragment_base_view, null);

        //配置状态视图的方法
        initStatusLayout();


        //添加状态视图到根视图上
        initBaseView();


        //初始化标题栏
        initTitle();


        //绑定视图
//        ButterKnife.bind(CommonFragment.this, rootView);

        //注册EventBus
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init(rootView, savedInstanceState);
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            boolean isSupportHidden = savedInstanceState.getBoolean(STATE_SAVE_IS_HIDDEN);

            FragmentTransaction ft = getFragmentManager().beginTransaction();
            if (isSupportHidden) {
                ft.hide(this);
            } else {
                ft.show(this);
            }
            ft.commit();
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(STATE_SAVE_IS_HIDDEN, isHidden());
    }

    /**
     * 返回布局ID的方法
     *
     * @return
     */
    protected abstract int getLayoutId();

    /**
     * 初始化方法
     */
    protected abstract void init(View view, Bundle savedInstanceState);


    /**
     * 设置标题显示的方法,有些页面可能需要自定义头部所以提供该方法
     * true为显示,false为不显示
     */
    protected abstract boolean isNeedShowTitle();

    /**
     * 设置头部标题的方法
     */
    protected abstract String setTitleText();

    /**
     * 初始化状态管理栏目视图
     */
    protected void initStatusLayout() {
        statusLayoutManager = StateLayoutManager.newBuilder(getContext())
                .contentView(getLayoutId())
                .emptyDataView(R.layout.base_activity_emptydata)
                .errorView(R.layout.base_activity_error)
                .loadingView(R.layout.base_fragment_loading)
                .netWorkErrorView(R.layout.base_activity_networkerror)
                .build();
    }


    /**
     * 提供给子类设置加载布局背景的方法
     *
     * @param colorId
     */
    protected void setLoadingBg(int colorId) {
        if (statusLayoutManager != null) {
            RelativeLayout rlOutSide = statusLayoutManager.getRootLayout().findViewById(R.id.rl_loading_out);
            rlOutSide.setBackgroundColor(colorId);
        }
    }

    /**
     * 将状态视图添加到根视图上
     */
    private void initBaseView() {
        LinearLayout ll_main = rootView.findViewById(R.id.ll_main);
        ll_main.addView(statusLayoutManager.getRootLayout());
        //使用注解绑定
//        ButterKnife.bind(BaseActivity.this);
    }


    /**
     * 初始化标题栏的方法
     */
    private void initTitle() {
        //找到头布局
        llHead = rootView.findViewById(R.id.ll_base_head);
        //返回
        rlBack = rootView.findViewById(R.id.rl_base_back);
        //标题
        tvTitle = rootView.findViewById(R.id.tv_base_title);

        //设置显示和隐藏的方法
        if (isNeedShowTitle()) {
            //一般Fragment里面是不需要显示返回键的
            llHead.setVisibility(View.VISIBLE);
            //隐藏返回键
            rlBack.setVisibility(View.GONE);
            tvTitle.setText(setTitleText());
        } else {
            llHead.setVisibility(View.GONE);
        }

    }


    /**
     * EventBus的接受事件的方法
     *
     * @param busInfo
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void busEvent(BusInfo busInfo) {

    }


    /**
     * 显示Activity内容视图的方法
     * 如果当前Activity页面没有网络请求操作时,在init()方法中直接调用该方法
     */
    protected void showContent() {
        statusLayoutManager.showContent();
    }

    /**
     * 显示空数据视图的方法
     */
    protected void showEmptyData() {
        statusLayoutManager.showEmptyData();
        LinearLayout ll_empty_data = rootView.findViewById(R.id.ll_empty_data);
        ll_empty_data.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                init(rootView, null);
            }
        });
    }


    /**
     * 网络请求错误需要显示的页面
     */
    protected void showError() {
        statusLayoutManager.showError();
        LinearLayout ll_error_data = rootView.findViewById(R.id.ll_error_data);
        ll_error_data.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                init(rootView, null);
            }
        });
    }

    /**
     * 无Wifi或者4G网络时提示用户打开网络设置的方法
     * 该方法一般在基类中通过工具类判断是否有检测到网络,然后处理即可
     */
    protected void showNetWorkError() {
        statusLayoutManager.showNetWorkError();
        LinearLayout ll_set_network = rootView.findViewById(R.id.ll_set_network);
        ll_set_network.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent("android.settings.WIRELESS_SETTINGS");
                startActivity(intent);
            }
        });
    }

    /**
     * 显示加载框的方法
     */
    protected void showLoading() {
        statusLayoutManager.showLoading();
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.activity = (Activity) context;
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

}
